package com.hyt.it.ogt.ksmonitor.statistics.mq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hyt.common.apiInfor.ApiResponse;
import com.hyt.it.ogt.ksmonitor.statistics.model.CandidateStatisticsAddVO;
import com.hyt.it.ogt.ksmonitor.statistics.rpc.KwStatisticsClient;
import com.hyt.it.ogt.ksmonitor.statistics.service.IMonitorStatisticsService;
import com.hyt.it.ogt.ksmonitor.statistics.service.IMonitorStatisticsSubmitService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Objects;

/**
 * 视频监考数据统计
 *
 * @author 朱振宇
 * @since 2022-12-02
 */
@Component
@Slf4j
@ConditionalOnClass(name = "com.hyt.it.ogt.kw.Application")
public class MonitorStatisticsMqConsumer {
    @Resource
    private IMonitorStatisticsService iMonitorStatisticsService;
    @Resource
    private KwStatisticsClient kwStatisticsClient;
    @Resource
    private IMonitorStatisticsSubmitService iMonitorStatisticsSubmitService;

    private static final int KW_SUCCESS_CODE = 20000;

    @RabbitListener(bindings = {@QueueBinding(value = @Queue( value = "${mq.monitorstatistics.queue}",
            autoDelete = "false",durable = "true"),
            exchange = @Exchange( value = "${mq.monitorstatistics.exchange}" ,type = ExchangeTypes.DIRECT),
            key = {"${mq.monitorstatistics.route}"})})
    public void monitorStatisticsMqListener(String json, Message message, Channel channel) throws IOException {
        log.info("视频监考数据统计消费队列消息: {}", json);
        try {
            CandidateStatisticsAddVO candidateStatisticsAddVO = JSON.parseObject(json, CandidateStatisticsAddVO.class);
            if (Objects.isNull(candidateStatisticsAddVO.getRoomId()) && Objects.nonNull(candidateStatisticsAddVO.getCandidateId())) {
                try {
                    String res = kwStatisticsClient.getRoomIdByCandidateId(candidateStatisticsAddVO.getCandidateId());
                    ApiResponse<String> response = ApiResponse.ConvertRet(res, String.class);
                    if (Objects.nonNull(response)) {
                        if (KW_SUCCESS_CODE == response.getCode().intValue()) {
                            candidateStatisticsAddVO.setRoomId(response.getData());
                        } else {
                            throw new Exception("根据考生ID查询虚拟考场ID异常：code=" + response.getCode());
                        }
                    }
                } catch (Exception e) {
                    log.error("根据考生ID查询虚拟考场ID异常，重新放入队列进行消费，candidateStatisticsAddVO={}", JSONObject.toJSONString(candidateStatisticsAddVO));
                    iMonitorStatisticsSubmitService.addNum(candidateStatisticsAddVO.getExamId(),
                            candidateStatisticsAddVO.getStatisticsType(),
                            candidateStatisticsAddVO.getCandidateId(),
                            candidateStatisticsAddVO.isRepeat(),
                            (int) candidateStatisticsAddVO.getNum());
                    return;
                }
            }
            iMonitorStatisticsService.addTotal(candidateStatisticsAddVO);
        } catch (Exception e) {
            log.error("视频监考数据统计消费队列消息保存异常: 【{}】------{}", json, e);
        } finally {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
